package com.smedi.ismedi.web.starter.handler;

import com.smedi.ismedi.authority.starter.util.VerifyHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

import static com.smedi.ismedi.authority.starter.constant.AuthorityConstant.ISMEDI_ACCESS_INFO;
import static com.smedi.ismedi.authority.starter.constant.AuthorityConstant.ISMEDI_ACCESS_TOKEN;
import static com.smedi.ismedi.authority.starter.context.CurrentUserHelper.infoContext;
import static com.smedi.ismedi.authority.starter.context.CurrentUserHelper.tokenContext;

/**
 * 检验当前服务是否包含了ticket
 */
@Slf4j
@AllArgsConstructor
public class CatchFromRequestSessionAttributeHandler implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token = httpServletRequest.getHeader(ISMEDI_ACCESS_TOKEN);

        // 从cookie中获取token。此处是为了适配前端不传token的情况，可能有CSRF问题产生，同时不支持第三方网站
        if (VerifyHelper.isNotAvailable(token)) {
            Cookie[] cookies = httpServletRequest.getCookies();
            if (VerifyHelper.isAvailable(cookies)) {
                Cookie cookieWithToken  = Arrays.stream(cookies).filter(cookie -> cookie.getName().equals(ISMEDI_ACCESS_TOKEN)).findAny().orElse(null);
                if (VerifyHelper.isAvailable(cookieWithToken)) {
                    token = cookieWithToken.getValue();
                }
            }
        }

        String info = httpServletRequest.getHeader(ISMEDI_ACCESS_INFO);

        tokenContext.set(token);
        infoContext.set(info);


//        // 获取请求内容的信息
//        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
//        while (headerNames.hasMoreElements()) {
//            String attribute = headerNames.nextElement();
//            String value = httpServletRequest.getHeader(attribute);
//
//            if (attribute.contains(WebParameterConstant.headerTag)) {
//                String name = attribute.replaceAll(WebParameterConstant.headerTag, "");
//                httpServletRequest.getSession().setAttribute(name, value);
//                list.add(attribute);
//            }
//        }
//
//        if (list.size() > 0) {
//            log.debug("请求地址: {}", httpServletRequest.getRequestURI());
//            log.debug("头请求参数迁移完成: {}", list);
//        }
//
//        Class<? extends HttpServletRequest> clazz = httpServletRequest.getClass();
//        Field[] fields = clazz.getDeclaredFields();
//        Optional<Field> request = Arrays.stream(fields).filter(field -> "request".equals(field.getName())).findFirst();
//        if (request.isPresent()) {
//            request.get().setAccessible(true);
//            Optional<Field> coyoteRequest = Arrays.stream(
//                    request.get().get(httpServletRequest).getClass().getDeclaredFields()
//            ).filter(field -> "coyoteRequest".equals(field.getName())).findFirst();
//
//            if (coyoteRequest.isPresent()) {
//                coyoteRequest.get().setAccessible(true);
//                Optional<Field> headers = Arrays.stream(
//                        coyoteRequest.get().get(request.get().get(httpServletRequest)).getClass().getDeclaredFields()
//                ).filter(field -> "headers".equals(field.getName())).findFirst();
//
//                if (headers.isPresent()) {
//                    headers.get().setAccessible(true);
//
//                    MimeHeaders mimeHeaders = (MimeHeaders) headers.get().get(coyoteRequest.get().get(request.get().get(httpServletRequest)));
//                    list.stream().forEach(attribute -> {
//                        mimeHeaders.removeHeader(attribute);
//                    });
//                }
//            }
//        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        // logger.info("--------------处理请求完成后视图渲染之前的处理操作---------------");

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        // logger.info("---------------视图渲染之后的操作-------------------------0");
    }
}
